<?php
/**
 * 客户跟进记录控制器
 */

namespace app\controller\customer;

use app\BaseController;
use app\model\customer\CustomerTrace as CustomerTraceModel;
use app\model\admin\User as UserModel; // 引入User模型
use app\model\Customer as CustomerModel; // 引入Customer模型
use think\facade\Db;

class Trace extends BaseController
{
    /**
     * 无需登录的方法
     * @var array
     */
    protected $noNeedLogin = []; // 移除list和view，恢复到需要登录的状态
    
    /**
     * 查看客户跟进记录列表
     */
    public function list()
    {
        $cid = input('cid');
        $customer_id = input('customer_id');
        $admin_id = input('admin_id');
        $keywords = input('keywords');
        $page = input('page', 1);
        $limit = input('limit', 10);
        
        $where = [];
        // 优先使用customer_id参数，如果没有再使用cid参数
        if ($customer_id) {
            $where[] = ['ct.cid', '=', $customer_id];
        } elseif ($cid) {
            $where[] = ['ct.cid', '=', $cid];
        }
        
        // 如果提供了管理员ID，添加关联查询条件
        if ($admin_id) {
            $where[] = ['ct.admin_id', '=', $admin_id];
        }
        
        // 如果提供了关键词，添加内容模糊搜索
        if ($keywords) {
            $where[] = ['ct.content', 'like', '%' . $keywords . '%'];
        }
        // 添加条件：只查询未删除的记录
        $where[] = ['ct.delete_time', '=', 0];
        
        try {
            // 使用直接查询而不是使用关联，避免潜在的错误
            $query = Db::name('customer_trace')
                ->alias('ct')
                ->leftJoin('oa_admin u', 'ct.admin_id = u.id')
                ->leftJoin('customer c', 'ct.cid = c.id')
                ->field('ct.*, u.username, u.nickname, c.name as customer_name')
                ->where($where)
                ->order('ct.create_time', 'desc');
                
            // 获取总数
            $total = $query->count();
            
            // 分页查询
            $list = $query->page($page, $limit)->select()->toArray();
            
            // 处理数据
            foreach ($list as &$item) {
                // 处理管理员名称
                $item['admin_name'] = $item['nickname'] ?: $item['username'];
                unset($item['nickname'], $item['username']);
                
                // 确保时间字段是整数
                if (isset($item['create_time']) && $item['create_time']) {
                    $item['create_time'] = (int)$item['create_time'];
                }
                
                if (isset($item['follow_time']) && $item['follow_time']) {
                    $item['follow_time'] = (int)$item['follow_time'];
                }
                
                if (isset($item['next_time']) && $item['next_time']) {
                    $item['next_time'] = (int)$item['next_time'];
                }
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list,
                'count' => $total
            ]);
        } catch (\Exception $e) {
            // 记录详细的错误信息到日志
            \think\facade\Log::error('获取跟进记录列表失败: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 查看单个客户跟进记录
     */
    public function view()
    {
        $id = input('id');
        if (!$id) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        try {
            // 使用直接查询而不是使用关联，避免潜在的错误
            $trace = Db::name('customer_trace')
                ->alias('ct')
                ->leftJoin('oa_admin u', 'ct.admin_id = u.id')
                ->leftJoin('customer c', 'ct.cid = c.id')
                ->field('ct.*, u.username, u.nickname, c.name as customer_name')
                ->where('ct.id', $id)
                ->find();
            
            if (!$trace) {
                return json(['code' => 1, 'msg' => '记录不存在']);
            }
            
            // 处理管理员名称
            $trace['admin_name'] = $trace['nickname'] ?: $trace['username'];
            unset($trace['nickname'], $trace['username']);
            
            // 确保时间字段是整数
            if (isset($trace['create_time']) && $trace['create_time']) {
                $trace['create_time'] = (int)$trace['create_time'];
            }
            
            if (isset($trace['follow_time']) && $trace['follow_time']) {
                $trace['follow_time'] = (int)$trace['follow_time'];
            }
            
            if (isset($trace['next_time']) && $trace['next_time']) {
                $trace['next_time'] = (int)$trace['next_time'];
            }
            
            return json(['code' => 0, 'msg' => 'success', 'data' => $trace]);
        } catch (\Exception $e) {
            // 记录详细的错误信息到日志
            \think\facade\Log::error('获取跟进记录详情失败: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 新建客户跟进记录
     */
    public function add()
    {
        $data = input('post.');
        
        // 确保follow_time和next_time是整数
        if (isset($data['follow_time'])) {
            $data['follow_time'] = (int)$data['follow_time'];
        } else {
            $data['follow_time'] = 0;
        }
        
        // 修改next_time处理，确保值为整数，支持'0'、0和null均转为0
        if (isset($data['next_time'])) {
            $data['next_time'] = (int)$data['next_time'];
        } else {
            $data['next_time'] = 0;
        }
        
        $data['admin_id'] = $this->getUserId();
        $data['create_time'] = time();
        
        try {
            $result = CustomerTraceModel::create($data);
            if ($result) {
                return json(['code' => 0, 'msg' => '添加成功', 'data' => ['id' => $result->id]]);
            } else {
                return json(['code' => 1, 'msg' => '添加失败', 'data' => []]);
            }
        } catch (\Exception $e) {
            // 记录详细的错误日志
            \think\facade\Log::error('添加跟进记录失败: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
            return json(['code' => 10501, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }

    /**
     * 编辑客户跟进记录
     */
    public function edit()
    {
        $id = input('id');
        if (!$id) {
            return json(['code' => 1, 'msg' => '参数错误', 'data' => []]);
        }
        
        $data = input('post.');
        
        // 确保follow_time和next_time是整数
        if (isset($data['follow_time'])) {
            $data['follow_time'] = (int)$data['follow_time'];
        } else {
            $data['follow_time'] = 0;
        }
        
        // 修改next_time处理，确保值为整数，支持'0'、0和null均转为0
        if (isset($data['next_time'])) {
            $data['next_time'] = (int)$data['next_time'];
        } else {
            $data['next_time'] = 0;
        }
        
        $data['update_time'] = time();
        
        try {
            $result = CustomerTraceModel::where('id', $id)->update($data);
            if ($result) {
                return json(['code' => 0, 'msg' => '编辑成功', 'data' => ['id' => $id]]);
            } else {
                return json(['code' => 1, 'msg' => '编辑失败', 'data' => []]);
            }
        } catch (\Exception $e) {
            return json(['code' => 10501, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }
    
    /**
     * 删除客户跟进记录（软删除）
     */
    public function del()
    {
        $id = input('id');
        if (!$id) {
            return json(['code' => 1, 'msg' => '参数错误', 'data' => []]);
        }
        
        $result = CustomerTraceModel::where('id', $id)->update(['delete_time' => time()]);
        if ($result) {
            return json(['code' => 0, 'msg' => '删除成功', 'data' => ['id' => $id]]);
        } else {
            return json(['code' => 1, 'msg' => '删除失败', 'data' => []]);
        }
    }
}
